﻿using Microsoft.AspNetCore.Authentication.Cookies;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Mvc;
using SignalR.Web.Models;
using System.Security.Claims;
using Microsoft.Extensions.Caching.Memory;
using SignalR.Web.Hubs; 
using Microsoft.AspNetCore.SignalR;
using System.Runtime.InteropServices;

namespace SignalR.Web.Controllers
{
    public class LoginController : Controller
    {
        private readonly ILogger<LoginController> _logger;
        private IMemoryCache _cache;
		private IHubContext<ChatHub> _chatHub;
		public LoginController(ILogger<LoginController> logger, IMemoryCache cache, IHubContext<ChatHub> chatHub)
        {
            _logger = logger;
			_cache = cache;
			_chatHub = chatHub;

		}

        public IActionResult Index()
        {
            return View();
        }
        [HttpPost]
		public async Task<IActionResult> AccountAsync(LoginModel model)
		{
			var account = model.Account;
			var pwd = model.Pwd; 

			var info = TestUsers.UserList.Find(u => u.UserName == model.Account && u.Password == model.Pwd);
			if (info == null)
			{
				var res = new { success = false, msg = "账号或密码错误" };
				return Ok(res);
			}


			//创用户信息
			var claimsIdentity = new ClaimsIdentity("Cookies");
			//添加用户声明信息
			claimsIdentity.AddClaim(new Claim(ClaimTypes.NameIdentifier, info.Id.ToString()));
			claimsIdentity.AddClaim(new Claim(ClaimTypes.Name, info.UserName));
			claimsIdentity.AddClaim(new Claim(ClaimTypes.Role, info.Role));
            claimsIdentity.AddClaim(new Claim(ClaimTypes.GroupSid, info.GroupName));
            
            //创建ClaimsPrincipal
            var userClaimPrincipal = new ClaimsPrincipal(claimsIdentity);

			//在Http上下文中，使用用户信息设置凭证并指定验证方案
			await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, userClaimPrincipal);


			try
			{
				await RedisHelper.SetAsync(string.Format(WebConstCacheKey.UserCacheKey, model.Account), model);
			}
			catch (Exception ex)
			{

				throw ex;
			}
		


			_cache.Set(string.Format(WebConstCacheKey.UserCacheKey,model.Account), model);

            ResultModel result = new ResultModel();
            result.Code = 0;
            result.Msg = info.UserName + "登陆成功";
			result.OnlineUser=  WebConst.OnlineUserList;

			await _chatHub.Clients.Groups(info.GroupName).SendAsync("LoginResponse", result);


		   var redisValue=	await RedisHelper.GetAsync(string.Format(WebConstCacheKey.UserCacheKey, model.Account));


			return Ok(result);
		}
        [HttpGet]
        public async Task<IActionResult> LogOutAsync()
        {
            //登出并删除Cookie中的用户凭证
            await HttpContext.SignOutAsync();
			 
            return View("Index");
        }

  //      [HttpGet]
		//public async Task<IActionResult> LogOutAsync()
		//{
		//	//登出并删除Cookie中的用户凭证
		//	await HttpContext.SignOutAsync();

		//	var data = new { success = true, msg = "登出成功" };

		//	return Ok(data);
		//}

		[HttpGet]
		public IActionResult AccessDenied()
		{ 
			return View();
		}
		
	}
}